package com.audio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AudioRecorderActivity extends Activity implements
		AudioManager.OnAudioFocusChangeListener {
	/** Called when the activity is first created. */

	private boolean turnOffMic = false;

	private static final String CONFIG_PATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/config.properties";

	private Properties settings = new Properties();

	private TextView dbLevelTxtView;

	private Thread audioReaderThread;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button vibrateToggleBtn = (Button) this
				.findViewById(R.id.vibrateToggleButton);
		vibrateToggleBtn.setOnClickListener(new VibrateToggleBtnListener());

		Button powerBtn = (Button) this.findViewById(R.id.powerBtn);
		powerBtn.setOnClickListener(new PowerBtnListener());

		dbLevelTxtView = (TextView) this.findViewById(R.id.dbLevel);

		// AudioManager audioManager = (AudioManager)
		// getSystemService(Context.AUDIO_SERVICE);
		//
		// if (turnOffMic) {
		// audioManager.setMicrophoneMute(true);
		// return;
		// }
		//
		// // Record audio
		// Recorder recorderInstance = new Recorder();
		// short[] recordedAudioBuffer = null;
		//
		// AudioTrack audioTrack = null;
		//
		// // Write the audio to the file
		// audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
		// AudioFormat.CHANNEL_CONFIGURATION_STEREO,
		// AudioFormat.ENCODING_DEFAULT, 4096, AudioTrack.MODE_STREAM);
		//
		// recordedAudioBuffer = recorderInstance.startRecording();
		// recorderInstance.stopRecording();
		//
		// short[] recording_tracks = recorderInstance.getRecordedAudioBuffer();
		//
		// // calculate the relative DB power. 0 is the maximum, and -100 is the
		// // minimum
		// Double dbPower = SignalPower.calculatePowerDb(recording_tracks, 0,
		// recordedAudioBuffer.length);
		//
		// dbLevelTxtView.setText(dbPower.toString());

		// int result = audioManager.requestAudioFocus(this,
		// AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		//
		// if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
		// return;
		// }
		//
		// audioTrack.setStereoVolume(1.0f, 1.0f);
		// audioTrack.play();
		// audioTrack.write(recording_tracks, 0, recordedAudioBuffer.length);
		//
		// audioTrack.stop();
		// audioTrack.flush();
		//
		// audioManager.abandonAudioFocus(this);

	}

	@Override
	public void onAudioFocusChange(int focusChange) {
		switch (focusChange) {
		case AudioManager.AUDIOFOCUS_GAIN:
			break;
		case AudioManager.AUDIOFOCUS_LOSS:
			break;
		default:
			break;
		}

	}

	private Properties readSettings() {
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream(CONFIG_PATH));
		} catch (IOException e) {
			e.printStackTrace();
		}

		return properties;
	}

	private void saveSettings() {
		FileOutputStream out;

		try {

			File f = new File(CONFIG_PATH);

			if (!f.exists()) {
				f.createNewFile();
			}

			out = new FileOutputStream(f);
			settings.storeToXML(out, "settings");
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	private class PowerBtnListener implements OnClickListener {
		public PowerBtnListener() {

		}

		@Override
		public void onClick(View v) {

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					readAudio();
				}});
			// need to start this in a separate thread so that it wont hold up
			// the application.
			
//			
//				Handler refresh = new Handler();
//				refresh.post(audioReaderThread = new Thread(new Runnable() {
//					@Override
//					public void run() {
//						readAudio();
//					}
//				}, "Audio Reader"));
//
//				audioReaderThread.start();

			
		}

		private void readAudio() {
			// Record audio
			Recorder recorderInstance = new Recorder();
			short[] recordedAudioBuffer = null;

			AudioTrack audioTrack = null;

			// Write the audio to the file
			audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
					AudioFormat.CHANNEL_CONFIGURATION_STEREO,
					AudioFormat.ENCODING_DEFAULT, 4096, AudioTrack.MODE_STREAM);

			recordedAudioBuffer = recorderInstance.startRecording();
			recorderInstance.stopRecording();

			short[] recording_tracks = recorderInstance
					.getRecordedAudioBuffer();

			// calculate the relative DB power. 0 is the maximum, and -100 is
			// the
			// minimum
			Double dbPower = SignalPower.calculatePowerDb(recording_tracks, 0,
					recordedAudioBuffer.length);

			dbLevelTxtView.setText(dbPower.toString());
			
					
		}

	}

	private class VibrateToggleBtnListener implements OnClickListener {
		public VibrateToggleBtnListener() {

		}

		public void onClick(View v) {
			// create and load default properties
			settings.put("VIBRATE_IND", "YES");
			saveSettings();
		}

	}

	private void thingsToDoWhenThresholdReach() {

		// vibrate the phone
		Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

		long milliseconds = 500;
		v.vibrate(milliseconds);

		// show notification at the status bar
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		int icon = R.drawable.icon;
		CharSequence tickerText = "Hello";
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);

		Context context = getApplicationContext();
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this,
				AudioRecorderActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);

	}

}